﻿
Imports System.IO
Imports std

Public Class counter
    Inherits loghandler

    Public Shadows Const backupConfignaming As String = "counter"
    Public Const counterFileSuffix As String = ".counter.log"
    Protected writer As StreamWriter = Nothing
    Protected counter As map(Of String, UInt64) = Nothing
    Protected flushtally As tally = Nothing

    Protected Overrides Sub initial()
        Dim logfile As String = Nothing
        logfile = defaultOutputfile(configNaming.defaultValue.counter.outputpath) + counterFileSuffix
        If Not createWriter(writer, logfile) Then
            raiseError("cannot create writer for file " + logfile + ", cannot handle request." _
                       , errorHandle.errorType.system)
        End If
        flushtally = New tally(configParameter(configNaming.counter.flushtimes _
                                               , configNaming.defaultValue.counter.flushtimes))
    End Sub

    Protected Overrides Sub oneline(ByRef log As String, ByRef casename As String)
        Static times As UInt64 = 0
        counter(casename) += 1
        times += 1
        If times = maxUInt64 Then
            times = 0
        End If
        If flushtally.tick() AndAlso Not writer Is Nothing Then
            writer.BaseStream.Seek(0, SeekOrigin.Begin)
            writer.BaseStream.SetLength(0)
            Dim it As map(Of String, UInt64).iterator = Nothing
            it = counter.begin()
            While it <> counter.end()
                writer.WriteLine((+it).first + character.tab + Convert.ToString((+it).second))
                it += 1
            End While

            writer.Flush()
            writer.BaseStream.Flush()
        End If
    End Sub

    Public Sub New()
        caseConfigNaming = configNaming.counter.counter
        multimatch = configNaming.defaultValue.counter.multimatch
        MyBase.backupConfignaming = backupConfignaming
        counter = New map(Of String, UInt64)()
    End Sub
End Class
